package cn.com.my.yes1;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 使用org.json解析
 * @author chenhs
 * @time 2015年7月8日 下午7:23:11
 */
public class OrgJson {
	
	public static void writeJson(){
		JSONObject obj = new JSONObject();
		obj.put("name", "mkyong.com");
		obj.put("age", new Integer(100));
	 
		JSONArray list = new JSONArray();
		list.put("msg 1");
		list.put("msg 2");
		list.put("msg 3");
		obj.put("messages", list);
	 
		try {
			FileWriter file = new FileWriter("c:\\test1.json");
			file.write(obj.toString());
			file.flush();
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	 
		System.out.print(obj);
	}
	
	
	@SuppressWarnings("resource")
	public static void readJson(){
		StringBuilder sb = new StringBuilder();
		
		try {
			BufferedReader reader = new BufferedReader(new FileReader("c:\\test1.json"));
			String line = null;
			while ((line = reader.readLine()) != null){
				sb.append(line).append("\n");
			}
			
			System.out.println(sb.toString());
			JSONObject jsonObject = new JSONObject(sb.toString());
			String name = (String) jsonObject.getString("name");
			System.out.println(name);
			
			long age = (Long) jsonObject.getLong("age");
			System.out.println(age);
			
			
			JSONArray returnArray = jsonObject.getJSONArray("messages");
			
			for(int i=0; i<returnArray.length();i++){
				System.out.println(returnArray.getString(i));
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		
	}
	
	public static void main(String[] args) {
//		writeJson();
		readJson();
	}

}
